package com.harmony.pilot.agent.tools;

import com.harmony.pilot.agent.model.*;
import com.harmony.pilot.common.dto.CodeContext;
import com.harmony.pilot.common.dto.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 代码生成工具
 */
@Component
@Slf4j
public class CodeGenerationTool implements AgentTool {
    
    private final RestTemplate restTemplate;
    
    @Value("${services.generation.url:http://localhost:8082}")
    private String generationServiceUrl;
    
    public CodeGenerationTool(@Autowired(required = false) RestTemplate restTemplate) {
        this.restTemplate = restTemplate != null ? restTemplate : new RestTemplate();
    }
    
    @Override
    public String getName() {
        return "code_generation";
    }
    
    @Override
    public String getDescription() {
        return "根据自然语言描述生成C++代码";
    }
    
    @Override
    public String getParametersSchema() {
        return """
            {
              "type": "object",
              "properties": {
                "description": {
                  "type": "string",
                  "description": "代码生成描述"
                },
                "type": {
                  "type": "string",
                  "enum": ["function", "class", "generic"],
                  "description": "生成类型"
                },
                "filePath": {
                  "type": "string",
                  "description": "目标文件路径"
                }
              },
              "required": ["description"]
            }
            """;
    }
    
    @Override
    public boolean canHandle(Intent intent, ConversationContext context) {
        return intent.getType() == Intent.IntentType.CODE_GENERATION;
    }
    
    @Override
    public double getRelevanceScore(Intent intent, ConversationContext context) {
        if (intent.getType() == Intent.IntentType.CODE_GENERATION) {
            return 0.95;
        }
        return 0.0;
    }
    
    @Override
    public ToolResult execute(ToolRequest request) {
        Map<String, Object> params = request.getParameters();
        if (params == null) {
            params = new HashMap<>();
        }
        
        String description = (String) params.get("description");
        String type = (String) params.getOrDefault("type", "generic");
        String filePath = (String) params.get("filePath");
        
        if (description == null || description.isEmpty()) {
            description = request.getUserMessage();
        }
        
        if (description == null || description.isEmpty()) {
            return ToolResult.error("未提供代码生成描述");
        }
        
        try {
            // 构建生成请求
            Map<String, Object> genRequest = new HashMap<>();
            genRequest.put("type", type);
            genRequest.put("prompt", description);
            genRequest.put("maxLength", 2000);
            
            CodeContext codeContext = new CodeContext();
            codeContext.setProjectRoot(request.getContext().getProjectRoot());
            if (filePath != null) {
                codeContext.setFilePath(filePath);
            } else {
                codeContext.setFilePath(request.getContext().getCurrentFile());
            }
            genRequest.put("context", codeContext);
            
            // 调用代码生成服务
            RestResult<String> result = restTemplate.postForObject(
                generationServiceUrl + "/generate",
                genRequest,
                RestResult.class
            );
            
            if (result == null || !result.isSuccess()) {
                return ToolResult.error("代码生成失败: " + 
                    (result != null ? result.getMessage() : "服务无响应"));
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("code", result.getData());
            data.put("type", type);
            data.put("filePath", codeContext.getFilePath());
            
            return ToolResult.success("代码生成成功", data);
        } catch (Exception e) {
            log.error("Failed to generate code", e);
            return ToolResult.error("代码生成失败: " + e.getMessage());
        }
    }
}

